#include <signal.h>

static sighandler_t __signal_handler_stub[_NSIG] = {0};

static int __check_signal(int signum)
{
    switch (signum)
    {
    case SIGINT:
    case SIGILL:
    case SIGABRT:
    case SIGFPE:
    case SIGSEGV:
    case SIGTERM:
        return 0;
    default:
        break;
    }
    return -1;
}

static void __signal_handler(NX_SignalInfo * info)
{
    if (__signal_handler_stub[info->signal])
    {
        __signal_handler_stub[info->signal]((int)info->signal);
    }
}

sighandler_t signal(int signum, sighandler_t handler)
{
    NX_SignalAttr attr;
    NX_SignalHandler sigHandler;
    
    if (__check_signal(signum))
    {
        return SIG_ERR;
    }

    if (handler == SIG_DFL)
    {
        sigHandler = NX_SIGNAL_HANDLER_DEFAULT;
    }
    else if (handler == SIG_IGN)
    {
        sigHandler = NX_SIGNAL_HANDLER_IGNORE;
    }
    else
    {
        sigHandler = __signal_handler;
        __signal_handler_stub[signum] = handler;
    }

    NX_SignalInitAttr(&attr, sigHandler, 0);
    if (NX_SignalSetAttr((NX_Signal)signum, &attr) != NX_EOK)
    {
        return SIG_ERR;
    }
    return SIG_DFL;
}
